<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('执行和展示')"/>
    <meta charset="utf-8">
    <title>执行和展示</title>

    <link th:href="@{/easyui/themes/default/easyui.css}" rel="stylesheet" type="text/css"/>
    <link th:href="@{/easyui/themes/icon.css}" rel="stylesheet" type="text/css"/>
    <link th:href="@{/easyui/demo/demo.css}" rel="stylesheet" type="text/css"/>


    <!--  编辑器codemirror 官网https://codemirror.net/   下载源码 https://github.com/sql-formatter-org/sql-formatter -->
    <link th:href="@{/codemirror/lib/codemirror.css}" rel="stylesheet" type="text/css"/>
    <script th:src="@{/codemirror/codemirror.js}" type="text/javascript"></script>
    <!-- 相关主题   -->
    <link th:href="@{/codemirror/theme/eclipse.css}" rel="stylesheet" type="text/css"/>
    <link th:href="@{/codemirror/theme/idea.css}" rel="stylesheet" type="text/css"/>
    <link th:href="@{/codemirror/theme/ssms.css}" rel="stylesheet" type="text/css"/>
    <!-- 高亮   -->
    <script th:src="@{/codemirror/mode/sql/sql.js}" type="text/javascript"></script>
    <link th:href="@{/codemirror/addon/hint/show-hint.css}" rel="stylesheet"/>
    <script th:src="@{/codemirror/addon/hint/sql-hint.js}" type="text/javascript"></script>
    <script th:src="@{/codemirror/addon/hint/show-hint.js}" type="text/javascript"></script>

    <!--    sql格式化  https://github.com/sql-formatter-org/sql-formatter/releases -->
    <!--    下载源码 打包 1.npm install -g yarn   2.yarn install   3.yarn build  4，dist包下拿到对应的压缩好的js   -->
    <script th:src="@{/sqlformatter/sql-formatter.min.js}" type="text/javascript"></script>

    <style>
        div#searchTabs .panel-body {
            background: #fff;
            border: 1px solid #e7eaec;
            border-radius: 2px;
            padding: 0 !important;
            position: relative;
        }

    </style>
</head>
<body class="easyui-layout">
<div data-options="region:'north',border:false" style="height:260px;">
    <div id="operator" class="panel-header panel-header-noborder  " style="padding:0px;height:auto">
        <div>
            <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-diy-run1" plain="true"
               onclick="run();">执行(F8)</a>
            <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-diy-clear1" plain="true"
               onclick="clearSQL()">清空(F7)</a>
            <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-diy-update1" plain="true"
               onclick="formatSQL()">格式化(F9)</a>
            <a href="javascript:void(0)" class="easyui-menubutton" id="commonSqlBtn" iconCls="icon-diy-commonuse1"
               plain="true">常用SQL</a>
        </div>
        <div style="width:100%;height:260px;">
            <textarea id="sqltextarea"
                      style="margin:10px; font-size:14px;font-family: '微软雅黑';width:99.5%;height:100%; "></textarea>
        </div>
    </div>
</div>
<div data-options="region:'center'" style="height:97%;padding:0px">
    <div id="searchTabs" class="easyui-tabs"
         data-options="fit: true, border: false, showOption: true, enableNewTabMenu: true, enableJumpTabMenu: true">
        <div id="searcHomePanel" data-options="title: '消息', iconCls: 'icon-tip'">
            <textarea id="executeMessage"
                      style="margin:8px; font-size:12px;font-family: '微软雅黑';width:98.5%;height:98%; "
                      readonly> </textarea>
        </div>
    </div>
</div>

<!-- 添加模块 -->
<div id="adddlg" class="easyui-dialog" style="width:600px;height:400px;padding:10px 20px"
     closed="true" closable="false" modal="true" buttons="#dlg-buttons">
    <form id="addfm" method="post" novalidate>
        <input name="id" type="hidden"/>
        <table cellpadding="5">
            <tr>
                <td>名称:</td>
                <td><input name="name" class="easyui-textbox" type="text" required="true" missingMessage="不能为空"/></td>
            </tr>
            <tr>
                <td>SQL:</td>
                <td>
                    <input id="commonSqlAdd" name="commonSql" style="width:100%;height:100%" required="true"
                           missingMessage="不能为空"/>
                </td>
            </tr>
        </table>
    </form>
</div>
<div id="dlg-buttons">
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel"
       onclick="javascript:$('#adddlg').dialog('close')">取消</a>
    <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onclick="saveAddFm()">保存</a>
</div>

<!-- 常用SQL管理模块 -->
<div id="commonSqlMngDlg" class="easyui-dialog" maximized="true"
     closed="true" closable="true" modal="true">
    <table id='commonSqlMngDg' style="width:100%;height:100%"></table>
</div>
<th:block th:include="include :: footer"/>
<script th:src="@{/easyui/jquery.easyui.min.js}" type="text/javascript"></script>
<script th:src="@{/fly/fly.js}" type="text/javascript"></script>
<script th:src="@{/selfjs/FlyRequest.js}" type="text/javascript"></script>
<script th:src="@{/commonjs/CommonParam.js}" type="text/javascript"></script>

<style>
    .easyui-layout .pagination {
        display: inline-block;
        padding-left: 0;
        margin: 5px 0 !important;
        border-radius: 4px;
    }

</style>
<script type="text/javascript">
    var prefix = ctx + "datamonitor/excuteAndShow";
    let ctxPath = '[[${#servletContext.contextPath}]]';
    let resultTabCnt = 0;

    let editor = CodeMirror.fromTextArea(document.getElementById("sqltextarea"), {
        lineNumbers: true,
        matchBrackets: true,
        hintOptions: {
            completeSingle: false,
            completeOnSingleClick: true
        },
        styleActiveLine: true, // 高亮选中行
        indentUnit: 4,
        mode: "text/x-mysql",
        lineWrapping: true,
        theme: 'eclipse',
        autofocus: true,
        extraKeys: {
            ctrl: "autocomplete",
            F7: function () {
                clearSQL()
            }, F8: function () {
                run()
            }, F9: function () {
                formatSQL();
            }
        }
    });


    editor.refresh();
    editor.focus();

    editor.on('inputRead', (e, value) => {
        // 排除空格
        var text = value.text[0]
        if (!text || $.trim(text) == '') {
            return
        }
        e.showHint()
    })

    let execMessage = CodeMirror.fromTextArea(document.getElementById("executeMessage"), {
        mode: "text/x-mysql",
        theme: 'eclipse',
        lineNumbers: true,
        autofocus: false,
        readOnly: true
    });

    $(function () {
        $('#commonSqlAdd').textbox({
            multiline: true,
            width: 470,
            height: 230
        })
    });


    // 格式化sql
    function formatSQL() {
        var sqlContent = editor.getValue()
        editor.setValue(sqlFormatter.format(sqlContent))
    }

   var execSqlKeyWord = [ 'select', 'insert', 'update', 'delete', 'drop', 'create', 'show', 'explain', 'comment', 'alter' ];

    function isExecuteSql(sql) {
        var lowerSql = sql.toLowerCase();
        var flag = false;
        for (let i = 0; i < execSqlKeyWord.length; i++) {
            var word = execSqlKeyWord[i];
            if(lowerSql.indexOf(word) != -1) {
                flag = true;
                break;
            }
        }
        return flag;
    }

    function run() {
        let runSql = $.trim(editor.getValue()), textSelected = editor.getSelection();
        if (textSelected != '') {
            runSql = textSelected;
        }

        if (!runSql) {
            $.modal.alertWarning('请输入SQL语句');
            return;
        }
       // var stringWithoutComments = runSql.replace(/(\/\*[^*]*\*\/)|(\/\/[^*]*)|(--[^.].*)/gm, '');
        let runSqlSplit = runSql.split(";");
        for (let index = 0; index < runSqlSplit.length; index++) {
           var tempSql =  $.trim(runSqlSplit[index]);
            if (tempSql == '') {
                continue;
            }
            if (!isExecuteSql(tempSql)) {
                $.modal.alertWarning('执行的语句错误,请仔细检查！');
                return;
            }
        }
        let submitData = {};
        submitData['runSql'] = runSql;
        submitData['databaseId'] = getDatabaseId();


        var config = {
            url: prefix + '/executeSql',
            type: "post",
            dataType: "json",
            data: submitData,
            beforeSend: function () {
                $.modal.loading("正在处理中，请稍候...");
                $.modal.disable();
                //开始前先关闭其它
                for (let n = 1; n <= resultTabCnt; n++) {
                    $("#searchTabs").tabs("close", '结果' + n);
                }
                resultTabCnt = 0;
            },
            success: function (result) {
                $.modal.closeLoading();
                if (result.code == 0) {
                    var runLog = result.data.runLog;
                    execMessage.setValue(runLog);
                    execMessage.refresh();
                    var resultList = result.data.resultList;
                    for (let n = 1; n <= resultList.length; n++) {
                        $("#searchTabs").tabs("add", {
                            title: "结果" + n,
                            content: " <div id='pg" + n + "' style='height:30px' class='easyui-pagination'></div><div><table id='result" + n +
                                "' style='padding:0px;height:calc(100% - 30px);width:98.3%'></table></div>",
                            closable: true,
                            iconCls: "icon-diy-table1"
                        });

                        let domResult = '#result' + n;
                        $(domResult).datagrid({
                            data: resultList[n - 1]['rows']
                            , columns: [resultList[n - 1]['columns']]
                            , autoRowHeight: true
                            , rownumbers: true
                            , singleSelect: true
                        });

                        let domPg = '#pg' + n;
                        $(domPg).pagination({
                            pageList: COMMONPARAM_PAGELIST,
                            pageSize: resultList[n - 1]['pageSize'],
                            total: resultList[n - 1]['total'],
                            pageNumber: resultList[n - 1]['pageNum'],
                            beforePageText: '第',
                            afterPageText: '页    共 {pages} 页',
                            displayMsg: '当前显示 {from} - {to}条记录,共{total}条记录',
                            onSelectPage: function (pageNumber, pageSize) {
                                pagingList(pageNumber, pageSize, resultList[n - 1]['executeSql'], domResult, domPg);//选择第几页的时候，就刷新
                            },
                        });
                        resultTabCnt++;
                    }
                } else if (result.code == 301) {
                    $.modal.alertWarning(result.msg);
                } else {
                    $.modal.alertError(result.msg);
                }
            }, complete: function () {
                $.modal.closeLoading();
            }
        };
        $.ajax(config)
    }


    function pagingList(pageNum, pageSize, sql, domResult, domPg) {
        var databaseId = getDatabaseId();
        let submitData = {};
        submitData['sql'] = sql;
        submitData['databaseId'] = databaseId;
        if (sql == undefined || sql.trim() == '') {
            $.modal.alertWarning('sql不能为空');
        }
        submitData['pageNum'] = pageNum;
        submitData['pageSize'] = pageSize;

        var config = {
            url: prefix + '/list',
            type: "post",
            dataType: "json",
            data: submitData,
            success: function (result) {
                if (result.code == 0) {
                    var resultList = result.data
                    $(domResult).datagrid("loadData", resultList.rows);
                    $(domPg).pagination({
                        pageList: COMMONPARAM_PAGELIST,
                        pageSize: resultList.pageSize,
                        total: resultList.total,
                        pageNumber: resultList.pageNum,
                        beforePageText: '第',
                        afterPageText: '页    共 {pages} 页',
                        displayMsg: '当前显示 {from} - {to}条记录,共{total}条记录',
                        onSelectPage: function (pageNumber, pageSize) {
                            pagingList(pageNumber, pageSize, resultList.sql, domResult, domPg);//选择第几页的时候，就刷新
                        },
                    });
                } else if (result.code == 301) {
                    $.modal.alertWarning(result.msg);
                } else {
                    $.modal.alertError(result.msg);
                }
            }
        };
        $.ajax(config)
    }


    function clearSQL() {
        editor.setValue('');
    }

    function getDatabaseId() {
        var databaseId = $('#databaseId', parent.document).val();
        if (!databaseId) {
            $.modal.alertError('请选择数据库再进行操作！');
            throw new Error('请选择数据库再进行操作！');
        }
        return databaseId;
    }

</script>
</body>